package com.lute.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.mail.MailSender;
import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.model.Client;
import com.lute.model.ClientProfile;
import com.lute.model.Employee;
import com.lute.model.EmployeeCurrentState;
import com.lute.model.EmployeeProfile;
import com.lute.model.MailTemplate;
import com.lute.model.Position;
import com.lute.model.PositionName;
import com.lute.model.Role;
import com.lute.model.User;
import com.lute.utils.CreateMailForm;
import com.lute.utils.DAOFactory;
import com.lute.utils.SendMail;
import com.lute.utils.ServerErrorResponse;

@Controller
public class NewEmployeeProfileUpdateServlet {
	
//	private static final String access1 = "employee";
//	private static final String access2 = "approver";
	
	@RequestMapping(value="/newUserProfileUpdate",method = RequestMethod.POST,headers = "Content-type=application/json")
	public @ResponseBody String employeeModifyProfile(@RequestBody String newEmployeeJSON,HttpServletRequest request) throws JSONException {
		String result = "";
		String email;
		String clientId;
		int prevClientId = -1;
		String prevClient = "";
		JSONObject jsonReq;
		JSONObject jsonRes = new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		try {
			jsonReq = new JSONObject(newEmployeeJSON);
			email = jsonReq.getString("email");
			clientId = jsonReq.getString("clientId");
		} catch(JSONException e) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		
		/* check if json data was not malformed */
		if( (jsonReq.isNull("email")) && (jsonReq.isNull("clientId")) ) {
			jsonRes.put("result",ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		
		/* check  authorization */
		String access = (String)session.getAttribute("profile");
		
		if( !((access.equals("noProfile")) || (access.equals("created"))) ) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
		}
		
		String firstName = (String)session.getAttribute("firstName");
		String lastName = (String)session.getAttribute("lastName");
		String login = (String)session.getAttribute("login");
		String password = (String)session.getAttribute("password");
		String ldapEmail = (String)session.getAttribute("ldapEmail");
		String profile = (String)session.getAttribute("profile");

		if( !(jsonReq.isNull("email")) ) {
			boolean emailValidate = SendMail.getInstance().isValidEmailAddress(email);
			if(!emailValidate) {
				jsonRes.put("result", ServerErrorResponse.INVALID_EMAIL.toString());
				result = jsonRes.toString();
				return result;
			}
		} else {
			email = ldapEmail;
		}
		
		if(clientId == null) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		/* check if client exist in DataBase */
		Client client = Client.isClientRegistered(Integer.parseInt(clientId));
		if(client == null) {
			jsonRes.put("result", ServerErrorResponse.UNKNOWN_CLIENT.toString());
			result = jsonRes.toString();
			return result;
		}
		
		try {
			
			if(profile.equals("noProfile")) {
				Role employeeRole = DAOFactory.getInstance().getLuteInterface().getRoleFromDataBase("name", "employee");
				Employee employee = new Employee(firstName,lastName,login,email,employeeRole);
				EmployeeProfile employeeProfile = new EmployeeProfile(employee);
				/*TODO: new employee as developer role ??? */
				Position position = new Position();
				position.setName(PositionName.DEVELOPER.toString());
				position.setCreativity_percentage(PositionName.DEVELOPER.getPercentage());
				Position.addPositionToDB(position);
				employeeProfile.setPositions(position);
				employeeProfile.setClient(client);
				employeeProfile.setEmail(email);
				employeeProfile.setEmployeeCurrentState(EmployeeCurrentState.NOT_CONFIGURED.toString());
				employee.setEmployeeProfil(employeeProfile);
				int userId = Employee.addNewEmployeeToDB(employee);
				session.setAttribute("sessionUserId", userId);
				session.setAttribute("profile", "created");
				CreateMailForm.prepareMailsInCaseNewEmployeeRegistered(client, employee);
	
			} else {
				Integer userId = (Integer)session.getAttribute("sessionUserId");
				EmployeeProfile employeeProfile = EmployeeProfile.getEmployeeProfileByEmployeeIdFromDB("employee", userId);
				if(employeeProfile.getEmployeeCurrentState().equals(EmployeeCurrentState.NOT_CONFIGURED.toString())) {
					jsonRes.put("result", ServerErrorResponse.LOGOUT_REQUEST);
					result = jsonRes.toString();
					return result;
				}
				prevClientId = employeeProfile.getClient().getId_client();
				boolean isProfileChanged = false;
				
				/* check if employee wants to change the client selection if its state is not configured */
				if( (employeeProfile.getEmployeeCurrentState().equals(EmployeeCurrentState.NOT_CONFIGURED.toString())) &&
						(client != null) && (!(prevClientId == client.getId_client())) ) {
					
					String oldClientName = employeeProfile.getClient().getName();
					isProfileChanged = true;
					/*FIXME: Shall be sent after database will be updated */
					CreateMailForm.prepareMailsInCaseEmployeeProfileChanged(client, oldClientName, employeeProfile);
					employeeProfile.setClient(client);
				}
				if(!employeeProfile.getEmail().equals(email)) {
					employeeProfile.setEmail(email);
					isProfileChanged = true;
				}
				if(isProfileChanged) {
					User user = User.getUserFromDB("id_user", userId);
					user.setEmail(email);
					User.updateUserInDB(user);
					EmployeeProfile.updateEmployeeProfileInDB(employeeProfile);
				}
			}
		}catch(NullPointerException npe) {
			jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
			result = jsonRes.toString();
			System.out.println(result);
			return result;
		}
		
		jsonRes.put("result","OK");
		result = jsonRes.toString();
		return result;
	}
}
